import React, { useState, useEffect } from 'react';
import { ProLayout, MenuDataItem } from '@ant-design/pro-components';
import { Link, useAppData, Outlet } from 'umi';
import { Avatar, Dropdown, Space, message } from 'antd';
import { authApi } from '@/services/api';
import { 
  UserOutlined, 
  LogoutOutlined, 
  SettingOutlined,
  DashboardOutlined,
  TeamOutlined,
  SafetyOutlined,
  KeyOutlined,
  MenuOutlined,
  PayCircleOutlined,
  BarChartOutlined,
  MonitorOutlined,
  ToolOutlined,
  ApiOutlined,
  CodeOutlined,
  FileSearchOutlined,
} from '@ant-design/icons';

interface UserMenu {
  id: number;
  name: string;
  path?: string;
  icon?: string;
  parentId?: number;
  children?: UserMenu[];
}

const BasicLayout: React.FC = () => {
  const { clientRoutes } = useAppData();
  const [userMenus, setUserMenus] = useState<UserMenu[]>([]);
  const [userPermissions, setUserPermissions] = useState<string[]>([]);
  const [currentUser, setCurrentUser] = useState<any>(null);

  const iconMap: { [key: string]: React.ReactNode } = {
    DashboardOutlined: <DashboardOutlined />,
    TeamOutlined: <TeamOutlined />,
    UserOutlined: <UserOutlined />,
    SafetyOutlined: <SafetyOutlined />,
    KeyOutlined: <KeyOutlined />,
    MenuOutlined: <MenuOutlined />,
    PayCircleOutlined: <PayCircleOutlined />,
    BarChartOutlined: <BarChartOutlined />,
    MonitorOutlined: <MonitorOutlined />,
    ToolOutlined: <ToolOutlined />,
    ApiOutlined: <ApiOutlined />,
    CodeOutlined: <CodeOutlined />,
    FileSearchOutlined: <FileSearchOutlined />,
  };

  const fetchUserInfo = async () => {
    try {
      const [menusResponse, permissionsResponse, profileResponse] = await Promise.all([
        authApi.getUserMenus(),
        authApi.getUserPermissions(),
        authApi.getCurrentUser(),
      ]);

      // 处理数据包装结构
      const menusData = menusResponse.data || menusResponse || [];
      const permissionsData = permissionsResponse.data || permissionsResponse || [];
      const profileData = profileResponse.data || profileResponse;

      setUserMenus(menusData);
      setUserPermissions(permissionsData);
      setCurrentUser(profileData);
    } catch (error: any) {
      console.error('获取用户信息失败:', error);
      const errorMessage = error?.response?.data?.message || error?.message || '获取用户信息失败';
      message.error(errorMessage);
      
      // 如果是401错误，清除token并重定向到登录页
      if (error?.response?.status === 401) {
        localStorage.removeItem('token');
        window.location.href = '/user/login';
      }
    }
  };

  const buildMenuItems = (menus: UserMenu[]): MenuDataItem[] => {
    return menus.map(menu => ({
      key: menu.path || menu.id.toString(),
      path: menu.path,
      name: menu.name,
      icon: menu.icon ? iconMap[menu.icon] : undefined,
      children: menu.children ? buildMenuItems(menu.children) : undefined,
    }));
  };

  const menuDataRender = (): MenuDataItem[] => {
    if (userMenus.length > 0) {
      return buildMenuItems(userMenus);
    }
    
    // 默认菜单（如果没有权限控制或获取失败时显示）
    return [
      {
        key: '/dashboard',
        path: '/dashboard',
        name: '仪表盘',
        icon: <DashboardOutlined />,
      },
      {
        key: '/auth',
        name: '权限管理',
        icon: <SafetyOutlined />,
        children: [
          {
            key: '/auth/users',
            path: '/auth/users',
            name: '用户管理',
            icon: <UserOutlined />,
          },
          {
            key: '/auth/roles',
            path: '/auth/roles',
            name: '角色管理',
            icon: <TeamOutlined />,
          },
          {
            key: '/auth/permissions',
            path: '/auth/permissions',
            name: '权限管理',
            icon: <KeyOutlined />,
          },
        ],
      },
      {
        key: '/business',
        name: '业务管理',
        icon: <BarChartOutlined />,
        children: [
          {
            key: '/business/payment',
            path: '/business/payment',
            name: '支付管理',
            icon: <PayCircleOutlined />,
          },
          {
            key: '/business/reports',
            path: '/business/reports',
            name: '报表管理',
            icon: <BarChartOutlined />,
          },
        ],
      },
      {
        key: '/monitor',
        path: '/monitor',
        name: '系统监控',
        icon: <MonitorOutlined />,
      },
    ];
  };

  const rightContentRender = () => {
    const menuItems = [
      {
        key: 'profile',
        icon: <UserOutlined />,
        label: '个人中心',
      },
      {
        key: 'settings',
        icon: <SettingOutlined />,
        label: '设置',
      },
      {
        type: 'divider' as const,
      },
      {
        key: 'logout',
        icon: <LogoutOutlined />,
        label: '退出登录',
      },
    ];

    return (
      <Space>
        <Dropdown
          menu={{
            items: menuItems,
            onClick: ({ key }) => {
              if (key === 'logout') {
                localStorage.removeItem('token');
                window.location.href = '/user/login';
              }
            },
          }}
        >
          <Space>
            <Avatar size="small" icon={<UserOutlined />} />
            <span>{currentUser?.nickname || currentUser?.username || '管理员'}</span>
          </Space>
        </Dropdown>
      </Space>
    );
  };

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      fetchUserInfo();
    }
  }, []);

  return (
    <ProLayout
      title="系统管理后台"
      logo="https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg"
      layout="mix"
      contentWidth="Fluid"
      fixedHeader
      fixSiderbar
      colorWeak={false}
      menuDataRender={menuDataRender}
      rightContentRender={rightContentRender}
      menuItemRender={(item, dom) => (
        <Link to={item.path || '/'}>{dom}</Link>
      )}
    >
      <Outlet />
    </ProLayout>
  );
};

export default BasicLayout;